<!DOCTYPE html>
<html>
<head>
    <title>原料取样修改</title>
    {% include 'system/common/header.html' %}
    <link rel="stylesheet" href="{{ url_for('static', filename='system/admin/css/other/user.css') }}"/>
</head>
<body class="pear-container">
{# 查询表单 #}
<div class="mainBox">
    <div class="main-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="" lay-filter="user-query-form">
            <div class="layui-form-item">
                 <label class="layui-form-label">单据日期</label>
                        <div class="layui-input-inline">
                            <input type="text" name="date_time" lay-verify="required|date"  autocomplete="off" placeholder="yyyy-MM-dd"
                   class="layui-input"  id="ID-laydate"  >
                        </div>
                {% if authorize("user:power:raw:yp:sampler") %}

                    <label class="layui-form-label">取样员</label>
                    <div class="layui-input-inline">
                       <select lay-verify="required" name="user_sampler_id" lay-filter="select-filter-user-keeper" id="select-keeper" >
                              <option value="{{ user_sampler.id }}">{{ user_sampler.realname }}</option>


                       </select>


                    </div>

                {% endif %}
                <label class="layui-form-label">单据编号</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="sample_dh" readonly autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" value="{{ info.sample_dh }}" >
                                    </div>



            </div>
            <div class="layui-form-item">
                 <label class="layui-form-label">取样方法</label>
                        <div class="layui-input-inline">
                            <select lay-verify="required"  disabled name="sample_project" lay-filter="select-filter-user-keeper"  >
                                <option value="{{ info.sample_project }}"  >{{ info.sample_project }}</option>
                                <option value="全项检验">药典取样通则</option>
                               <option value="部分检验">GMP附录取样管理</option>
                        </select>
                        </div>


                    <label class="layui-form-label">取样位置</label>
                    <div class="layui-input-inline">
                       <select lay-verify="required" disabled name="sample_department" lay-filter="select-filter-user-keeper"  >
                           <option value="{{ info.sample_department }}"  >{{ info.sample_department }}</option>
                           <option value="仓储部">仓储部</option>
                               <option value="生产车间一">生产车间一</option>
                        </select>


                    </div>


                  <label class="layui-form-label">取样类型</label>
                    <div class="layui-input-inline">
                       <select lay-verify="required" name="sample_type"  disabled id="sample_type"  >
                                <option value="{{ info.sample_type }}"  >{{ info.sample_type }}</option>
                               <option value="正常取样">正常取样</option>
                               <option value="临期取样">临期取样</option>
                                <option value="小样取样">小样取样</option>

                        </select>


                    </div>



            </div>
            <div class="layui-form-item">
                                    <label class="layui-form-label">备注</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="remark"  autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" value="{% if info.remark  %}{{ info.remark }}{% endif %} " id="ID_remark">
                                    </div>
                                </div>
            <div class="user-main user-collasped">
                <div class="layui-card">
                    <div class="layui-card-body">
                        <table id="user-table" lay-filter="user-table"></table>
                    </div>
                </div>
            </div>
            <div class="bottom">
                 <div class="button-container">
                        <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm"  lay-submit="" lay-filter="user-update" id="user-update">
                            <i class="layui-icon layui-icon-ok"></i>
                            提交
                        </button>

                    </div>
             </div>
        </form>
    </div>
</div>
    </div>
</div>

</body>
{# 表格操作 #}
<script type="text/html" id="user-toolbar">
    {% if authorize("store:raw:sample:edit:yp") %}
        <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
            <i class="pear-icon pear-icon-add"></i>
            其他功能
        </button>
    {% endif %}

</script>

{# 用户修改操作 #}
<script type="text/html" id="user-bar">

    {% if authorize("store:raw:sample:remove:yp") %}
        {% if info.verify_type != '小样请验' %}
            <button type="button" class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i
                    class="pear-icon pear-icon-ashbin"> 删除</i>
            </button>
        {% endif %}
    {% endif %}
</script>

{% raw %}

<script type="text/html" id="temp_pm">
      <div class="layui-input-wrap">

    <input type="text" lay-affix="search"   lay-filter="search" lay-options="{split: true}" placeholder="搜索…" class="layui-input" id="pm"
    value="{{ d.品名 }}" name="{{ d.LAY_INDEX }}">

  </div>

</script>
<script type="text/html" id="user-createTime">
    {{layui.util.toDateString(d.有效期至,  "yyyy-MM-dd")}}
</script>


{% endraw %}

{% include 'system/common/footer.html' %}

<script>
    layui.use(['table', 'form', 'jquery', 'popup'], function () {
        let table = layui.table
        let form = layui.form
        let $ = layui.jquery

        let popup = layui.popup

        var laydate = layui.laydate;
        let MODULE_PATH = "/store/raw/sample/yp/"
         // 获取当前日期

    const  d=new Date('{{ info.date_time }}')
      // 渲染
     laydate.render({
        elem: '#ID-laydate',
        value:"{{ info.date_time }}",
         min: new Date(d.getFullYear(), d.getMonth(),1).getTime(),
        max: new Date(d.getFullYear(), d.getMonth()+1, 0).getTime(),


      });
        //禁用Enter键表单自动提交
        document.onkeydown=function (event) {
            var target,code,tag;
            if(!event){
                event=window.event;//针对ie浏览器
                target=event.srcElement;
                code=event.keyCode;
                if(code==13){
                    tag=target.tagName;
                    if(tag=="TEXTAREA"){
                        return true;
                    }else{
                        return false
                    }
                }
            }else{
                target=event.target //遵循3c标准浏览器
                code=event.keyCode;
                if(code==13){
                    tag=target.tagName;
                    if(tag=="INPUT"){
                        return false;
                    }else{
                        return true
                    }
                }
            }
        }
         //获取采购人员、库管员、QA
        $.ajax({
                url: '/api/store/userYPyl',
                dataType: 'json',
                contentType: 'application/json',
                type: 'get',
                success: function (result) {

                  if (result.success) {

                     $('#select-keeper option[value !=""]').remove();

                    result.sampler.forEach(function(unit) {

                      // 创建新的 option 元素
                      var newOption = $('<option>', {
                        value: unit.id, // 设置 value 属性
                        text: unit.realname  // 设置显示文本
                      });
                      $("#select-keeper").append(newOption);
                    });

                    form.render('sselect')
                  } else {
                    layer.msg(result.msg, { icon: 2, time: 5000 })


                  }
                }
              });

         // 根据返回数据中某个字段来判断开启该行的编辑
      var editable = function(d){
          let a=form.val("user-query-form").verify_type
        if(a=='小样请验'){return 'text';}  // 这里假设以 editable 字段为判断依据
        else{ return ''  }
      };
        // 表格数据
        let cols = [
            [


                {title: '品名', field: '品名',templet: '#temp_pm', align: 'center'},
                {title: '简拼', field: '简拼', align: 'center'},
                {title: '规格', field: '规格', align: 'center'},
                {title: '批号', field: '批号', align: 'center'},
                {title: '产地', field: '产地', align: 'center'},

                 {title: '请验量', field: '请验量', align: 'center',edit:editable},
                 {title: '取样量', field: 'sample_number', align: 'center',edit:'text'},
                {title: '单位', field: '单位', align: 'center',edit:editable},



                {title: '操作', toolbar: '#user-bar', align: 'center', width: 180}
            ]
        ]
        let table_data = {{ rowdatas | tojson }} //把列表传入JS变量
        table_data.push({})
        // 渲染表格数据
        table.render({
            elem: '#user-table',
            data: table_data,
            id:'page_add-table',
            page: true,
            cols: cols,
            skin: 'line',
            height: 'full-148',
            toolbar: '#user-toolbar', /*工具栏*/
            text: {none: '暂无产品信息'},
            defaultToolbar: [{layEvent: 'refresh', icon: 'layui-icon-refresh'}, 'filter', 'print', 'exports'] /*默认工具栏*/
        })



        //

          // 输入框点缀事件 - 搜索示例

        form.on('input-affix(search)', function(obj){
            var elem = obj.elem; // 输入框
            var value = elem.value; // 输入框的值
            var name=elem.name; // 输入框的值

            // 模拟搜索跳转
            window.add(value,name)


        });
        table.on('tool(user-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj)
            }else if (obj.event === 'edit') {
                window.edit(obj)
            }
        });


        table.on('toolbar(user-table)', function (obj) {
            if (obj.event === 'add') {

            } else if (obj.event === 'refresh') {
                window.refresh()
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj)
            }
        })


        form.on('submit(user-update)', function (data) {
            {#layer.alert(JSON.stringify(data))#}
            var table_datas = table.cache['page_add-table'];
            Object.assign(data, {'table_datas':table_datas}) //字典增加合并另一个字典
            $.ajax({
                url: '/store/raw/sample/yp/update',
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: 'application/json',
                type: 'put',
                success: function (result) {
                    if (result.success) {
                        layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
                           parent.layui.table.reload('user-table')
                        })
                    } else {
                        layer.msg(result.msg, {icon: 2, time: 6000})
                    }
                }
            })
            return false
        })



        window.add = function (searchtext,rowid) {

            layer.open({
                type: 2,
                title: '新增',
                shade: 0.1,
                area: ['90%', '80%'],
                maxmin: true,

                moveOut:true,

                content: MODULE_PATH + 'add/frm_table?searchtext='+searchtext+'&sample_type='+form.val("user-query-form").sample_type,

                success: function(layero, index){
                  //layer.full(index); // 最大化


                },
                end: function() {
                    // 这里可以处理子窗口关闭时的逻辑
                    // 例如：更新父窗口的某些数据

                    var data = table.cache['page_add-table'];
                    // 获取某行数据，并从 data 中移除该行

                    {#layer.alert('混存数据'+JSON.stringify(data))#}

                    if(window.child_table_data.data.length ){
                        var new_ph = window.child_table_data.data[0].verify_dh
                        //判断是否为同一批号，如果是则进行，如果不是则报错
                        window.child_table_data.data.forEach((item,index,arr)=>{
                            if(String(item.verify_dh)===String(new_ph)){
                            }else{
                                window.child_table_data.data=[]
                                layer.alert('不是同一请验单号,不能一起请验2')
                                return
                            }

                        })

                        data.forEach((item,index,arr)=>{
                            if (Object.keys(item).length >3){

                                if(String(item.verify_dh)===String(new_ph)){
                                }else{
                                    window.child_table_data.data=[]
                                    layer.alert('不是同一请验单号,不能一起请验')
                                    return
                                    }
                            }

                            if(String(item.LAY_INDEX)===String(rowid)){

                                var sample_type=form.val("user-query-form").sample_type

                                Object.assign(item,window.child_table_data.data[0]) //字典增加合并另一个字典
                                //多选情况
                                window.child_table_data.data.forEach((item,index,arr)=>{
                                    if(index){
                                        data[data.length]=item
                                    }
                                })
                                 if (sample_type==='小样请验'){
                                      if (data.length>1){
                                          layer.alert('小样取样只能取样一个')
                                          data=[]
                                          return
                                      }
                                }
                                window.child_table_data.data=[]
                            }
                        })


                         if (Object.keys(data[data.length-1]).length > 3){
                            //获取字典的长度
                            data[data.length]={};





                        }






                        table.renderData('page_add-table');


                    }



                }
            })
            {#    window.open(MODULE_PATH + 'add','_blank');#}
        }



        window.remove = function (obj) {
            layer.confirm('确定要删除', {icon: 3, title: '提示'}, function (index) {
                layer.close(index)
                let loading = layer.load()

                if (Object.keys(obj.data).length > 2) {
                    // 获取当前实例的数据缓存
                    var data = table.cache['page_add-table'];
                    //只有一个在更新的时候就不能删除了
                    if(data.length===1){
                        popup.failure('只剩最后一行了，不能删除')
                        layer.close(loading)
                    }
                    table_data = table_data.filter(item => item.index !== obj.data.index);

                    {#obj.del()#}

                    // 获取某行数据，并从 data 中移除该行

                    var item = data.splice(obj.index , 1) // index 为当前行下标，一般可在事件中通过 obj.index 得到

                    // 将某行数据移动到另外某行

                    {#data.splice(newIndex, 0, item[0]);#}

                    table.renderData('page_add-table');
                    layer.close(loading)
                }else{
                    popup.failure('不能删除')
                    layer.close(loading)
                }

            })
        }


        window.refresh = function (param) {
            table.reload('user-table', {where: param})
        }
    })
</script>
</html>